package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {


    /**
     * 注入需要的bean对象
     */
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private AdminFeign adminFeign;

    @Autowired
    private AuthorMapper authorMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;



    @Autowired
    private ApArticleMapper apArticleMapper;


    @Value("${file.oss.web-site}")
    private String webSite;


    @Autowired
    private GeneratePageService generatePageService;

    /**
     * minio前缀
     */
    @Value("${file.minio.readPath}")
    private String readPath;


    @Autowired
    private RabbitTemplate rabbitTemplate;



    /**
     *  文章发布
     *  作者上传文章之后经过审核和人工审核之后会处于待发布状态
     *  有三个表 是 存储app端收看文章的
     *  所以需要将作者发布的文章有news 转化到app端的三个表中
     *  方便app端 收看
     *  分三个表的原因 : 减轻数据库的压力`
     * @param newsId 文章id
     */
    @Override
    public void publishArticle(Integer newsId) {
        //查询并检查需要处理的文章数据
        WmNews wmNews = getWmNews(newsId);

        //将文章封装成apArticle(app端的文章)
        ApArticle apArticle = getApArticle(wmNews);

        //保存或修改article
        saveOrUpdateArticle(apArticle);

        //保存关联配置和内容信息
        saveConfigAndContent(wmNews, apArticle);


        //  页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(),apArticle);


        //更新 news的状态  改为9  并设置   articleId
        updateWmNews(newsId, wmNews, apArticle);


        //TODO  通知es
        rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE,apArticle.getId());
        log.info("文章更新完毕,发送消息到es同步数据 id {}",apArticle.getId());
    }



    /**
     * 修改文章的状态为发布
     * @param newsId
     * @param wmNews
     * @param apArticle
     */
    private void updateWmNews(Integer newsId, WmNews wmNews, ApArticle apArticle) {
        //更改状态  修改为发布  状态为 9
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        //设置apArticle的id
        wmNews.setArticleId(apArticle.getId());
        //调用feign修改文章
        ResponseResult responseResult = wemediaFeign.updateWmNews(wmNews);
        //判断结果
        if(responseResult.getCode() != 0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用修改自媒体文章出错");
        }
    }


    /**
     * 保存关联的配置文件表 和 文章内容表
     * @param wmNews
     * @param apArticle
     */
    private void saveConfigAndContent(WmNews wmNews, ApArticle apArticle) {
        //添加文章配置信息对象
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        //设置  评论  转发  上下架   删除
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsDelete(false);
        apArticleConfigMapper.insert(apArticleConfig);

        //添加文章信息对象
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        //正文内容
        apArticleContent.setContent(wmNews.getContent());
        apArticleContentMapper.insert(apArticleContent);

    }


    /**
     * 保存或修改 apArticle
     * @param apArticle
     */
    private void saveOrUpdateArticle(ApArticle apArticle) {
        //判断apArticle是否存在id  如果有就是修改 如果 没有 就是保存
        if (apArticle.getId() == null){
            //表示保存
            //设置属性
            apArticle.setCollection(0); // 收藏数
            apArticle.setLikes(0);// 点赞数
            apArticle.setComment(0);// 评论数
            apArticle.setViews(0); // 阅读数
            //保存文章
            save(apArticle);

        }else {
//            //表示修改
//            ApArticle byId = getById(apArticle.getId());
//            if (byId == null){
//                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章信息不存在");
//            }
            //修改信息
            updateById(apArticle);
            //删除之前的关联表
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId,apArticle.getId()));
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId,apArticle.getId()));
        }
    }


    /**
     * 将需要发布的文章转化成 app 端的文章格式
     * @param wmNews
     * @return
     */
    private ApArticle getApArticle(WmNews wmNews) {
        //创建app端文章的对象
        ApArticle apArticle = new ApArticle();
        //将数据copy
        BeanUtils.copyProperties(wmNews,apArticle);
        //设置个别参数
        //设置id
        apArticle.setId(wmNews.getArticleId());
        //设置文章类型  默认普通文章
        apArticle.setFlag((byte)0);
        //设置布局  无图或有图  俩表字段不一样
        apArticle.setLayout(wmNews.getType());

        //远程调用查询文章的频道
        //adminFeign中的根据文章id查询频道
        ResponseResult<AdChannel> channelResult = adminFeign.findOne(wmNews.getChannelId());
        //判断feign调用状态
        if (channelResult.getCode() != 0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用查询频道出错");
        }
        //获取频道
        AdChannel channel = channelResult.getData();
        //判断数据
        if (channel == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"远程调用查询的频道不存在");
        }

        apArticle.setChannelId(wmNews.getChannelId());
        //插入频道
        apArticle.setChannelName(channel.getName());

        //设置作者信息 根据wmNews的id  查询作者的id
        LambdaQueryWrapper<ApAuthor> wrapper = Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId());
        //调用条件
        ApAuthor apAuthor = authorMapper.selectOne(wrapper);
        //判断数据
        if (apAuthor == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"作者信息不存在");
        }

        //插入作者信息
        apArticle.setAuthorId(Long.valueOf(apAuthor.getId()));
        apArticle.setAuthorName(apAuthor.getName());

        //将apArticle返回
        return apArticle;
    }


    /**
     * 查询需要发布的文章 并检查数据
     * @param newsId
     * @return
     */
    private WmNews getWmNews(Integer newsId) {
        //检查数据
        if (newsId == null){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"未找到该文章");
        }
        //根据id查询数据
        ResponseResult<WmNews> wmNewsResult = wemediaFeign.findNewById(newsId);
        //判断feign调用的状态
        if (wmNewsResult.getCode() != 0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程的调用查询文章出错");
        }
        //获取对象
        WmNews wmNews = wmNewsResult.getData();
        //判断数据
        if (wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"查询的文章不存在");
        }

        //判断文章的状态是否可发布
        short status = wmNews.getStatus().shortValue();
        if (WmNews.Status.ADMIN_SUCCESS.getCode() != status && WmNews.Status.SUCCESS.getCode() != status){
            //表示文章不在待发布状态
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章不在待发布状态,不能发布");
        }
        //表示数据没问题 将文章对象返回
        return wmNews;
    }


    /**
     * app端查询文章
     * @param loadtype 0为加载更多  1为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        //1 参数检查
        // 页大小
        Integer size = dto.getSize();
        if (size == null || size <=0){
            size = 10;
        }
        // 频道
        if (StringUtils.isBlank(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        // 时间
        if (dto.getMinBehotTime() == null){
            dto.setMinBehotTime(new Date());
        }
        if (dto.getMaxBehotTime() == null){
            dto.setMaxBehotTime(new Date());
        }
        // 类型判断
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW) && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE)){
            loadtype = ArticleConstants.LOADTYPE_LOAD_NEW;
        }
        //2 执行查询
        List<ApArticle> loadArticleList = apArticleMapper.loadArticleList(dto, loadtype);


        for (ApArticle apArticle : loadArticleList) {
            apArticle.setStaticUrl(readPath + apArticle.getStaticUrl());
        }


        //3 返回结果
        ResponseResult responseResult = ResponseResult.okResult(loadArticleList);
        responseResult.setHost(webSite);
        return responseResult;
    }


    /**
     *
     * @param loadtypeLoadMore
     * @param dto
     * @param firstPage
     * @return
     */
    @Override
    public ResponseResult load2(Short loadtypeLoadMore, ArticleHomeDTO dto, boolean firstPage) {
        //如果是首页
        if (firstPage){
            //
            String articleListJson = redisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(articleListJson)){
                List<ApArticle> apArticles = JSON.parseArray(articleListJson, ApArticle.class);
                for (ApArticle apArticle : apArticles) {
                    apArticle.setStaticUrl(readPath + apArticle.getStaticUrl());
                }
                ResponseResult responseResult = ResponseResult.okResult(apArticles);
                responseResult.setHost(webSite);
                return responseResult;
            }

        }

        return load(loadtypeLoadMore, dto);
    }
}